package com.sk.helper;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.sk.helper.R;
import com.sk.helper.base.BaseFragment;
import com.sk.helper.page.HomeFragment;
import com.sk.helper.page.TestFragment;
import com.sk.helper.service.ConnectionService;
import com.sk.helper.utils.FileUtils;
import com.sk.helper.utils.ShellUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;

public class MainActivity extends FragmentActivity {
    //@BindView(R.id.fl_content)
    FrameLayout flContent;
    //@BindView(R.id.rg_main)
    RadioGroup rgMain;
    //@BindView(R.id.rb_home)
    RadioButton rbHome;
    //@BindView(R.id.rb_rank)
    RadioButton rbDiscovery;


    //Context mContext;
    //@ViewInject(R.id.viewpager)
    // private NoScrollViewPager viewPager;
    //@Band(R.id.rb_main)
    //RadioGroup radioGroup;
    /**
     * 选中的Fragment的对应的位置
     */
    private int position;
    /**
     * 装4个页面
     */
    private List<BaseFragment> mBaseFragment;

    private Fragment tempFragment;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private Realm realm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.e("----sk--","MainActivity---");
       // Intent intent = new Intent(this, ConnectionService.class);
       // startService(intent);

        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorAppStyle,null));
        }else{
            this.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        //1.设置主页面
        setContentView(R.layout.activity_main);

        flContent = findViewById(R.id.fl_content);
        rgMain = findViewById(R.id.rg_main);
        rbHome = findViewById(R.id.rb_home);
        rbDiscovery = findViewById(R.id.rb_discovery);
        // ButterKnife.bind(this);

        initFragment();

        //设置RadioGroup的监听
        setListener();

        //verifyStoragePermissions(MainActivity.this);
        //将资源中的文件重写到sdcard中
        // writeStreamToFile(stream, file);

        try {
            FileUtils.copyAssetFileToFilesDir(this,"InjectServer.jar");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ShellUtils.CommandResult result = ShellUtils.execCommand("chmod 777 "+this.getFilesDir() + "/" + "InjectServer.jar", false);
        Log.e("MainActivity","CommandResult result-sk-"+result.result+"; success:"+result.successMsg+"; error:"+result.errorMsg);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(MainActivity.this)) {
                    Intent intent1 = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent1, 10);
                }
            }
        }
    }


    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }


    private void setListener() {
        //设置RadioGroup状态的监听
        rgMain.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        rgMain.check(R.id.rb_home);

    }

    private void initFragment() {
        mBaseFragment = new ArrayList<>();

        mBaseFragment.add(new HomeFragment());//添加主页面
        mBaseFragment.add(new TestFragment());//添加排行
        //mBaseFragment.add(new CategoryFragment());//添加发现
        // mBaseFragment.add(new UserFragment());//添加设置

    }


    /**
     * 根据位置得到对应的Fragment
     *
     * @return
     */
    public BaseFragment getFragment() {
        if (mBaseFragment!=null&&mBaseFragment.size()>0){

            BaseFragment fragment = mBaseFragment.get(position);
            return fragment;
        }
        return null;
    }


    private class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_home://主页
                    position = 0;
                    break;
                case R.id.rb_discovery://排行
                    position = 1;
                    break;
                default:
                    position = 0;
                    break;

            }

            //根据位置得到对应的Fragment
            BaseFragment to = getFragment();
            //替换
            switchFragment(tempFragment, to);

        }
    }

    /**
     * @param from 刚显示的Fragment,马上就要被隐藏了
     * @param to   马上要切换到的Fragment，一会要显示
     */
    private void switchFragment(Fragment from, Fragment to) {


        if (from != to) {
            tempFragment = to;
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            //才切换
            //判断有没有被添加
            if (!to.isAdded()) {
                //to没有被添加
                //from隐藏
                if (from != null) {
                    ft.hide(from);
                }
                //添加to
                if (to != null) {
                    ft.add(R.id.fl_content, to).commit();
                }
            } else {
                //to已经被添加
                //from隐藏
                if (from != null) {
                    ft.hide(from);
                }
                if (to != null) {
                    ft.show(to).commit();
                }
            }

        }
    }
/*
    private void switchFragment(BaseFragment to) {
        //1.得到FragmentManger
        FragmentManager fm = getSupportFragmentManager();
        //2.开启事务
        FragmentTransaction transaction = fm.beginTransaction();
        //3.替换
       // transaction.replace(R.id.fl_content,fragment);
        transaction.replace(R.id.fl_content,fragment);
        //4.提交事务
        transaction.commit();
    }*/

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        Log.e("onkeydown ==","keycode= "+keyCode);


        return super.onKeyDown(keyCode, event);


    }

    @Override
    protected void onResume() {

        Intent intent = new Intent(this, ConnectionService.class);
        intent.setAction(ConnectionService.ACTION_HIDE_PANEL);
        startService(intent);
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //stopService(new Intent(this, ConnectionService.class));
        //Log.e("11", "onDestroy--  mmmmmmmmmm   aaaa");
        realm.close();
    }

}

